package com.iw.adoms.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iw.adoms.utils.QrCodeUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Test;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iw.adoms.entity.Goods;
import com.iw.adoms.entity.QrBoxCode;
import com.iw.adoms.entity.QrGoodsCode;
import com.iw.adoms.entity.neum.DepartType;
import com.iw.adoms.entity.neum.Status;
import com.iw.adoms.service.GoodsService;
import com.iw.adoms.service.QrBoxCodeService;
import com.iw.adoms.service.QrGoodsCodeService;
import com.iw.core.orm.Filtration;
import com.iw.core.orm.Filtration.MatchType;
import com.iw.core.orm.PageData;
import com.iw.core.utils.PropertiesUtil;
import com.iw.core.utils.WebUtils;
import com.iw.core.utils.qrcode.TwoDimensionCode;

@Controller
@RequestMapping("/adoms/qrGoodsCode")
public class QrGoodsCodeAction {
    @Resource
    private QrGoodsCodeService qrGoodsCodeService;
    @Resource
    private QrBoxCodeService qrBoxCodeService;
    @Resource
    private GoodsService goodsService;

    @RequestMapping("/list")
    public ModelMap list(HttpServletRequest request) {
        PageData<QrGoodsCode> pageData = new PageData<QrGoodsCode>();
        // pageData.setPageSize(10);
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        pageData = qrGoodsCodeService.find(pageData);

        return new ModelMap(pageData);
    }

    private void commonModel(Model model) {
        List<QrBoxCode> boxList = qrBoxCodeService.findAll();
        model.addAttribute("boxList", boxList);
    }

    @RequestMapping(value = "/getGoodsByGCode")
    @ResponseBody
    public QrGoodsCode getGoodsByGCode(String qrCode) {
        qrCode = qrCode.trim().replace(" ", "");
        QrGoodsCode goods = qrGoodsCodeService.find("qrCode", qrCode);
        if (goods != null && goods.getState().equals(Status.WILL_IN.getValue())) {
            return goods; // 只返回待入库的数据
        }
        return null;
    }

    @RequestMapping(value = "/getGoodsOrBoxByCode")
    @ResponseBody
    public Map<String, Object> getGoodsOrBoxByCode(String qrCode) {
//        qrCode = qrCode.trim().replace(" ", "");
        //2013.10.10
        String wCode = QrCodeUtil.getCode(qrCode);
        Map<String, Object> map = new HashMap<String, Object>();
        // 先查询箱码
//        QrBoxCode box = qrBoxCodeService.find("qrCode", qrCode);
        QrBoxCode box = qrBoxCodeService.find("wCode", wCode);
        if (box != null && box.getState().equals(Status.WILL_IN.getValue())) {
            Filtration boxFilter = new Filtration(MatchType.EQ, box.getId(), "box.id");
            Filtration stateFilter = new Filtration(MatchType.EQ, Status.WILL_IN.getValue(), "state");
            List<QrGoodsCode> gList = qrGoodsCodeService.findList(boxFilter, stateFilter);
            if (gList != null && gList.size() > 0) {
                map.put("gList", gList);
                map.put("box", box);
                return map;
            } else {
                box.setState(Status.HAS_IN.getValue());
                qrBoxCodeService.update(box);
                return null;
            }
        }

//        QrGoodsCode goods = qrGoodsCodeService.find("qrCode", qrCode);
        QrGoodsCode goods = qrGoodsCodeService.find("wCode", wCode);
        if (goods != null && goods.getState().equals(Status.WILL_IN.getValue())) {
            goods.setMemo(goods.getBox().getGoodsNum().toString());
            map.put("goods", goods);
            return map; // 只返回待入库的数据
        }
        return null;
    }

    @RequestMapping(value = "/getQR")
    @ResponseBody
    public List<Map<String, Object>> create() {
        TwoDimensionCode handler = new TwoDimensionCode();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 20; i++) {
            Map<String, Object> qr = new HashMap<String, Object>();
            String img = new Date().getTime() + i + ".png";
            String imgPath = PropertiesUtil.QR_PATH + img;
            handler.encoderQRCode(i + "getQR", imgPath, "png");
            String imgUri = PropertiesUtil.QR_URI + img;
            qr.put("uri", imgUri);
            qr.put("path", imgPath);
            list.add(qr);
        }
        return list;
    }

    @RequestMapping(value = "/getQrGoodsByICode/{iCode}")
    public String getQrGoodsByICode(Model model, @PathVariable("iCode") String iCode) {
        iCode = iCode.trim().replaceAll(" ", "");
        // 2.省代出库后就可以积分（2013.04.21）
//        String hql = "from QrGoodsCode where id in (select g.qrCode.id from Goods g where g.department.id in (select dd.id from Department dd where dd.type.id in "
//                + "(select dt.id from DepartmentType dt where dt.name=?)) and g.state = ? and g.qrCode.id = " + "(select qq.id from QrGoodsCode qq where qq.iCode = ? and qq.state != ?))";
//        List<QrGoodsCode> qrList = qrGoodsCodeService.findList(hql, DepartType.SD.v(), Status.HAS_OUT.getValue(), iCode, Status.QR_HAD_INTEGRAL.getValue());

        //到达省代就可以积分 (2013.08.06 - 2013.10.10)
        String hql = "from QrGoodsCode where id in (select g.qrCode.id from Goods g where g.department.id in (select dd.id from Department dd where dd.type.id in "
                + "(select dt.id from DepartmentType dt where dt.name != ?))   and g.qrCode.id = " + "(select qq.id from QrGoodsCode qq where qq.iCode = ? and qq.state != ?))";
        List<QrGoodsCode> qrList = qrGoodsCodeService.findList(hql, DepartType.ZD.v(), iCode, Status.QR_HAD_INTEGRAL.getValue());

        if (qrList != null && !qrList.isEmpty()) {
            model.addAttribute("qrGoodsCode", qrList.get(0));
            List<Goods> gList = goodsService.findList("from Goods where qrCode.iCode = ? and 1=?", iCode, 1);
            if (gList != null && !gList.isEmpty()) {
                model.addAttribute("m", gList.get(0).getMarchandise());
                model.addAttribute("goods", gList.get(0));
            }
        } else {
            qrList = qrGoodsCodeService.findList("iCode", iCode);
            if (qrList != null && !qrList.isEmpty()) {
                model.addAttribute("qr", qrList.get(0));
            }
        }

        return "/adoms/qrGoodsCode/detailiCode";
    }

    @RequestMapping(value = "/qrImg")
    public void qrImg(String qr, HttpServletResponse response) {
        TwoDimensionCode handler = new TwoDimensionCode();
        try {
            handler.encoderQRCode(qr, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/print")
    public String print(Model model) {
        // List<QrBoxCode> boxList = qrBoxCodeService.findAll();
        // model.addAttribute("boxList", boxList);
        return "/adoms/qrGoodsCode/print";
    }

    @RequestMapping(value = "/printByBox")
    @ResponseBody
    public Map<String, Object> printByBox(Integer boxId) {
        Map<String, Object> map = new HashMap<String, Object>();
        QrBoxCode box = qrBoxCodeService.get(boxId);
        List<QrGoodsCode> goodsList = qrGoodsCodeService.findList("box.id", box.getId());
        map.put("box", box);
        map.put("goodsList", goodsList);
        return map;
    }

    @RequestMapping(value = "/new")
    public String addForm(Model model) {
        commonModel(model);
        return "/adoms/qrGoodsCode/input";
    }

    @RequestMapping(value = "/edit/{id}")
    public String editForm(@PathVariable("id") Integer id, Model model) {
        QrGoodsCode qrGoodsCode = qrGoodsCodeService.find(id);
        model.addAttribute(qrGoodsCode);
        commonModel(model);
        return "/adoms/qrGoodsCode/input";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(QrGoodsCode qrGoodsCode) {
        if (qrGoodsCode.isNew()) {
            qrGoodsCodeService.save(qrGoodsCode);
        } else {
            qrGoodsCodeService.update(qrGoodsCode);
        }

        return "redirect:/adoms/qrGoodsCode/list";// 重定向
    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        qrGoodsCodeService.delete(id);
        return "redirect:/adoms/qrGoodsCode/list";// 重定向
    }

    @RequestMapping(value = "/visible/{id}")
    public String visible(@PathVariable("id") Integer id) {
        qrGoodsCodeService.visible(id);
        return "redirect:/adoms/qrGoodsCode/list";// 重定向
    }

    @RequestMapping(value = "/unVisible/{id}")
    public String unVisible(@PathVariable("id") Integer id) {
        qrGoodsCodeService.unVisible(id);
        return "redirect:/adoms/qrGoodsCode/list";// 重定向
    }

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
    }

    /**
     * *** TEST *****
     */
    @Test
    public void writeMap2Json() {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> map2 = new HashMap<String, Object>();
            map.put("uname", 123);
            map2.put("map", map);
            ObjectMapper objectMapper = new ObjectMapper();
            // JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
            // jsonGenerator.writeObject(map);
            // objectMapper.writeValue(System.out, map);
            String s = objectMapper.writeValueAsString(map2);
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
